package com.lzx.iteam.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.*;
import com.lzx.iteam.EventDetailContentActivity;
import com.lzx.iteam.bean.aidl.EventReplyNewData;
import com.lzx.iteam.emotion.gif.AnimatedGifDrawable;
import com.lzx.iteam.emotion.gif.AnimatedImageSpan;
import com.lzx.iteam.widget.gridimg.MyGridView;
import com.lzx.iteam.util.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhangshuai on 15-5-26.
 */
public class EventReplyAdapter extends BaseAdapter {

    private List<EventReplyNewData> mData;
    private Context mContext;
    private EventDetailContentActivity mActivity;
    private MediaPlayUtil mMediaPlayUtil;
    private AnimationDrawable mImageAnim;
    private ViewHolder mViewHolder;
    private int mPosition;
    private ArrayList<String> mImageOri;
    String[] mImageThumb;
    StringBuilder mImages;
    private EventImageAdapter mImageAdapter;

    public EventReplyAdapter(List<EventReplyNewData> mData, Context mContext) {
        this.mData = mData;
        this.mContext = mContext;
        mMediaPlayUtil = MediaPlayUtil.getInstance();
        mActivity = (EventDetailContentActivity) mContext;
    }

    public void bindData(List<EventReplyNewData> mData) {
        if (this.mData != null) {
            this.mData.clear();
            this.mData.addAll(mData);
        } else {
            this.mData = new ArrayList<EventReplyNewData>();
            this.mData.addAll(mData);
        }
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int i) {
        return mData.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if (view == null) {
            holder = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(R.layout.event_reply_layout, viewGroup, false);
            holder.name = (TextView) view.findViewById(R.id.reply_tv_tmeme_host);
            holder.time = (TextView) view.findViewById(R.id.reply_tv_tmeme_time);
            holder.content = (TextView) view.findViewById(R.id.reply_tv_theme_content);
            holder.avatar = (ImageView) view.findViewById(R.id.event_iv_reply);
            holder.imageLayout = (MyGridView) view.findViewById(R.id.reply_image_layout);
            holder.voiceLayout = (LinearLayout) view.findViewById(R.id.reply_ll_voice);
            holder.voiceLen = (TextView) view.findViewById(R.id.reply_tv_voice_len);
            holder.voiceImage = (ImageView) view.findViewById(R.id.reply_iv_voice_image);
            holder.voiceAnim = (ImageView) view.findViewById(R.id.reply_iv_voice_image_anim);
            view.setTag(holder);

        } else {
            holder = (ViewHolder) view.getTag();
        }
        final EventReplyNewData data = mData.get(i);
        holder.name.setText(data.getUserName());
        holder.time.setText(DateUtil.getUpDateTime(Long.parseLong(data.getUpdateTime()) * 1000));
        if (!StringUtil.isEmpty(data.getContent())) {
            holder.content.setVisibility(View.VISIBLE);
            holder.voiceLayout.setVisibility(View.GONE);
            holder.imageLayout.setVisibility(View.GONE);
            SpannableStringBuilder sb = handler(holder.content,
                    data.getContent());
            holder.content.setText(sb);
        } else {
            holder.content.setVisibility(View.GONE);
        }

        if (StringUtil.isEmpty(data.getAvatar())) {
            Log.d("data.getAvatar()", "  kong  de  ");
        } else {
            ImageLoaderInterface.imageLoader.displayImage(data.getAvatar(), holder.avatar, ImageLoaderInterface.optionHeadImage);
        }

        if(data.getAttachments()!=null){
            try {
                JSONArray attachments = new JSONArray(data.getAttachments());
                mImageThumb = new String[attachments.length()];
                mImageOri = new ArrayList<String>();
                mImages = new StringBuilder();
                for (int j = 0; j < attachments.length(); j++) {
                    JSONObject attachment = attachments.getJSONObject(j);
                    if ("1".equals(attachment.getString("type"))) {
                        holder.imageLayout.setVisibility(View.VISIBLE);
                        holder.voiceLayout.setVisibility(View.GONE);
                        mImageOri.add(attachment.getString("ori"));
                        mImageThumb[j] = attachment.getString("thumb");
                        mImages.append(attachment.getString("thumb")).append(",");
                    } else {
                        holder.voiceLayout.setVisibility(View.VISIBLE);
                        holder.content.setVisibility(View.GONE);
                        holder.imageLayout.setVisibility(View.GONE);

                        if (!StringUtil.isEmpty(attachment.getString("data"))) {

                            holder.voiceLen.setText(attachment.getString("duration") + '"');

                            // TODO 防止语音正在播放时，滑动发生布局复用时发生混乱
                            if (mMediaPlayUtil.isPlaying()) {
                                if (mPosition != i) {
                                    holder.voiceImage.setVisibility(View.VISIBLE);
                                    holder.voiceAnim.setVisibility(View.GONE);
                                } else {
                                    holder.voiceImage.setVisibility(View.GONE);
                                    holder.voiceAnim.setVisibility(View.VISIBLE);
                                }
                            }

                            holder.voiceLayout.setOnClickListener(new AnimClick(holder, attachment.getString("data"), i));

                        }
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        String uid = PreferenceUtil.getInstance(mContext).getString(PreferenceUtil.CLIENT_USEID,"-1");
        if (!StringUtil.isEmpty(Constants.NEW_EVENT_REPLY_TIME) && Constants.NEW_EVENT_REPLY_TIME.equals(data.getUpdateTime()) && uid.equals(data.getUserId())){
            Log.d("event_new_reply","  one   int  here  " + Constants.NEW_EVENT_REPLY_TIME + "  ====  " +data.getUpdateTime());
            mImageAdapter = new EventImageAdapter(mContext, mImageThumb, mImageOri, mImages.toString().substring(0, mImages.length()), true);
        }else{
            mImageAdapter = new EventImageAdapter(mContext, mImageThumb, mImageOri, mImages.toString().substring(0, mImages.length()), data.getEventId());
        }

        holder.imageLayout.setAdapter(mImageAdapter);
        // 防止Item不可点击
        holder.imageLayout.setEnabled(false);
        holder.imageLayout.setClickable(false);

        holder.avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("0".equals(data.getUserId()) || StringUtil.isEmpty(data.getUserId())) {
                    Toast.makeText(mContext, "对不起，该用户未注册", Toast.LENGTH_LONG).show();
                } else {
                    Intent intent = new Intent(mContext, ContactNameCardActivity.class);
                    intent.putExtra("user_id", data.getUserId());
                    mContext.startActivity(intent);
                }
            }
        });

        holder.content.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                ((EventDetailContentActivity) mContext).showCopyPop(view, data.getContent());
                return false;
            }
        });


        return view;
    }

    class ViewHolder {
        TextView name;
        TextView time;
        TextView content;
        ImageView avatar;
        MyGridView imageLayout;
        LinearLayout voiceLayout;
        ImageView voiceImage;
        ImageView voiceAnim;
        TextView voiceLen;
    }


    private SpannableStringBuilder handler(final TextView gifTextView, String content) {
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            String tempText = m.group();
            try {
                String num = tempText.substring("#[face/png/f_static_".length(), tempText.length() - ".png]#".length());
                String gif = "face/gif/f" + num + ".gif";
                /**
                 * 如果open这里不抛异常说明存在gif，则显示对应的gif
                 * 否则说明gif找不到，则显示png
                 * */
                InputStream is = mContext.getAssets().open(gif);
                sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                is.close();
            } catch (Exception e) {
                String png = tempText.substring("#[".length(), tempText.length() - "]#".length());
                try {
                    int resID = mContext.getResources().getIdentifier(png.split("/")[2].substring(0, png.split("/")[2].indexOf(".")), "drawable", mContext.getApplicationInfo().packageName);
                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeResource(mContext.getResources(), resID)), m.start(), m.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

//                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeStream(mContext.getAssets().open(png))), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
//                e.printStackTrace();
            }
        }
        return sb;
    }

    class AnimClick implements View.OnClickListener {

        private ViewHolder viewHolder;
        private String voiceData;
        private int position;

        public AnimClick(ViewHolder viewHolder, String voiceData, int position) {
            this.viewHolder = viewHolder;
            this.voiceData = voiceData;
            this.position = position;
        }

        @Override
        public void onClick(View view) {
            // TODO 判断是不是之前点击的那条语音
            if (position == mPosition) {
                if (mMediaPlayUtil.isPlaying()) {
                    mMediaPlayUtil.stop();
                    mImageAnim.stop();
                    viewHolder.voiceImage.setVisibility(View.VISIBLE);
                    viewHolder.voiceAnim.setVisibility(View.GONE);
                } else {
                    startAnim(viewHolder);
                    String voicePath = "";
                    if (voiceData.startsWith("http") && voiceData.contains("7xk")) {
                        voicePath = voiceData;
                    } else {
                        voicePath = StringUtil.decoderBase64File(voiceData);
                    }
                    mMediaPlayUtil.play(voicePath);
                }
            } else {
                if (mMediaPlayUtil.isPlaying()) {
                    mMediaPlayUtil.stop();
                    mImageAnim.stop();
                    // TODO 停止之前语音的动画
                    mViewHolder.voiceImage.setVisibility(View.VISIBLE);
                    mViewHolder.voiceAnim.setVisibility(View.GONE);
                }
                startAnim(viewHolder);
                String voicePath = "";
                if (voiceData.startsWith("http") && voiceData.contains("7xk")) {
                    voicePath = voiceData;
                } else {
                    voicePath = StringUtil.decoderBase64File(voiceData);
                }
                mMediaPlayUtil.play(voicePath);
            }
            mPosition = position;
            mViewHolder = viewHolder;

        }
    }

    /**
     * 语音播放效果
     *
     * @param viewHolder
     */

    public void startAnim(final ViewHolder viewHolder) {

        mImageAnim = (AnimationDrawable) viewHolder.voiceAnim.getBackground();
        viewHolder.voiceAnim.setVisibility(View.VISIBLE);
        viewHolder.voiceImage.setVisibility(View.GONE);
        mImageAnim.start();
        mMediaPlayUtil.setPlayOnCompleteListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                viewHolder.voiceImage.setVisibility(View.VISIBLE);
                viewHolder.voiceAnim.setVisibility(View.GONE);
            }
        });
    }
}
